/*
https://leetcode-cn.com/problems/distribute-coins-in-binary-tree/solution/zai-er-cha-shu-zhong-fen-pei-ying-bi-by-leetcode/
 */
public class Solution979 {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int ans=0;

    public int distributeCoins(TreeNode root) {
        dfs(root);
        return ans;
    }

    private int dfs(TreeNode root) {
        if (root==null){
            return 0;
        }
        int a=dfs(root.left);
        int b=dfs(root.right);
        ans+=Math.abs(a)+Math.abs(b);
        return root.val+a+b-1;
    }

    public static void main(String[] args) {
        System.out.println(new Solution979().distributeCoins(new TreeNode(3,new TreeNode(0),new TreeNode(0))));
    }
}
